﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums;
using ZBJF.Warranty.Common.Enums.Certificate;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;
using ZBJF.Warranty.Model.ViewModel.Order;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class InsuranceOrderController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ToBeAuditedOrderList()
        {
            SystemUser user = ServiceFactory.SystemUserServiceInstance.Load(CurrentUser.ID);
            ViewBag.IsCheckOnline = user.IsCheckOnline.HasValue ? user.IsCheckOnline.Value : 0;
            return View();
        }
        public ActionResult AuditFaildOrderList()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(InsuranceOrderModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceOrderServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.CardNo,
                o.CardPwd,
                o.VerificationCertificate,
                o.OrderNO,
                o.InsuredAmount,
                o.ThirdOrderNO,
                o.InsuranceCompany,
                o.InsuranceCompanyBranch,
                o.InsuranceCategory,
                o.InsuranceCategoryName,
                o.ProductName,
                o.BuyType,
                BuyTypeDesc = EnumHelper.Instance.GetDescription(typeof(InsuranceBuyType), o.BuyType),
                o.Price,
                o.WaitDays,
                o.EffectiveDate,
                o.PolicyPeriod,
                o.PolicyPeriodUnit,
                o.UserName,
                o.UserPhone,
                o.CertificateType,
                CertificateTypeDesc = EnumHelper.Instance.GetDescription(typeof(UserCertificateType), o.CertificateType),
                o.CertificateNO,
                o.ProductTypeId,
                o.ProductTypeName,
                o.IMEI,
                o.ProductBrandId,
                o.ProductBrandName,
                o.ProductModelId,
                o.ProductModelName,
                o.SaleVendorId,
                o.SaleVendorName,
                o.SalePersonName,
                o.SaleManagerName,
                o.SaleManagerPhone,
                o.SaleAddress,
                o.OrderStatus,
                OrderStatusDesc = EnumHelper.Instance.GetDescription(typeof(InsuranceOrderStatus), o.OrderStatus),
                o.LastCheckUser,
                LastCheckTime = o.LastCheckTime.HasValue ? o.LastCheckTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                o.OrderFromType,
                OrderFromTypeDesc = EnumHelper.Instance.GetDescription(typeof(InsuranceOrderFromType), o.OrderFromType),
                CreateOrderTime = o.CreateOrderTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.CreateBy,
                o.LastModifyBy,
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss")
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }

        #region 投保审核页面
        public ActionResult Detail(int id)
        {
            var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(id);
            #region 基本保单信息
            //销售商编码
            string sellerCode = "";
            short checkTime = 0;
            if (order.SaleVendorId.HasValue)
            {
                Sellers sellerInfo = ServiceFactory.SellersServiceInstance.LoadByID(order.SaleVendorId.Value);
                if (sellerInfo != null)
                {
                    sellerCode = sellerInfo.SellerCode;
                    checkTime = sellerInfo.SellerInsuranceOrderCheckTime.HasValue ? sellerInfo.SellerInsuranceOrderCheckTime.Value : (short)0;
                }
            }
            ViewBag.sellerCode = sellerCode;
            ViewBag.checkTime = checkTime;

            //销售商产品名称
            string sellerProductName = "";
            //保险卡编码
            string productCardNo = null;
            if (order.SellerInsuranceProductID.HasValue)
            {
                SellerInsuranceProducts sellerInsuranceProduct = ServiceFactory.SellerInsuranceProductsServiceInstance.LoadById(order.SellerInsuranceProductID.Value);
                if (sellerInsuranceProduct != null)
                {
                    sellerProductName = sellerInsuranceProduct.ProductName;
                    //保险卡 获取保险卡编码
                    if (sellerInsuranceProduct.IsCardProduct)
                    {
                        var sellerInsuranceProductMappings = sellerInsuranceProduct.SellerInsuranceProductMappings.FirstOrDefault();
                        if (sellerInsuranceProductMappings != null && sellerInsuranceProductMappings.InsuranceProductPackageID.HasValue)
                        {
                            InsuranceProductPackage insuranceProductPackage = ServiceFactory.InsuranceProductPackageServiceInstance.LoadByID(sellerInsuranceProductMappings.InsuranceProductPackageID.Value);
                            if (insuranceProductPackage != null)
                            {
                                productCardNo = insuranceProductPackage.InsuranceProductPackageNO;
                            }
                        }
                    }
                }
            }
            ViewBag.productCardNo = productCardNo;
            ViewBag.sellerProductName = sellerProductName;
            #endregion


            #region 服务项目


            #endregion

            ////是否新机、新机期限、服务次数
            ////byte insuranceDeviceType = 100;
            ////int? newMachineInsuranceTimeLimit = null;
            ////int? serviceTimes = null;
            ////可用服务类型 这里不需要考虑保险卡的可服务类型。每次只能激活一个基础产品
            //List<int> warrantyMaintenanceTypes = new List<int>();
            //InsuranceProducts insuranceProduct = new InsuranceProducts();
            ////insuranceProduct.InsuranceDeviceType = 100;
            ////保险产品信息
            //if (order.InsuranceProductID.HasValue)
            //{
            //    insuranceProduct = ServiceFactory.InsuranceProductsServiceInstance.LoadByID(order.InsuranceProductID.Value);
            //    if (insuranceProduct != null)
            //    {
            //        //warrantyMaintenanceTypes = ServiceFactory.InsuranceProductWarrantyMaintenanceTypesServiceInstance.LoadEntities(t => t.InsuranceProductId == order.InsuranceProductID).Select(t => t.InsuranceWarrantyMaintenanceTypeId).ToList();
            //    }

            //}
            //ViewBag.insuranceProduct = insuranceProduct;
            //ViewBag.warrantyMaintenanceTypes = warrantyMaintenanceTypes;

            return View("InsuranceOrderDetail", order);//    //新页面
        }
        #endregion

        public ActionResult AuditOrder(int id)
        {
            var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(id);
            return View(order);
        }

        #region 审核保单信息 ActionResult AuditInsuranceOrder(InsuranceOrder model)
        [HttpPost]
        public ActionResult AuditInsuranceOrder(InsuranceOrder model)
        {
            var responseResult = new ResponseResult();
            var checkResut = Request["CheckResult"] != null && Convert.ToBoolean(Request["CheckResult"]);
            string msg = string.Empty;
            responseResult.Success = InsuranceOrderProvider.AuditInsuranceOrder(model.ID, checkResut, Request["CheckRemark"], CurrentUser.UserAccount, CurrentUser.UserDisPlayName, model.LastModifyTime, ref msg);
            responseResult.Message = msg;
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("Detail", new { id = model.ID });
        }
        #endregion

        #region 根据保单Id获取保单日志信息 JsonResult GetInsuranceOrderCheckLog(int insuranceOrderId)
        [HttpPost]
        public JsonResult GetInsuranceOrderCheckLog(int insuranceOrderId)
        {
            var logList =
                ServiceFactory.InsuranceOrderCheckLogServiceInstance.LoadByInsuranceOrderCheckLogId(insuranceOrderId)
                    .ToList()
                    .Select(o => new
                    {
                        o.ID,
                        o.CheckRemark,
                        CheckResult = o.CheckResult ? "审核通过" : "审核未通过",
                        CheckTime = o.CheckTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        o.CheckUserAccount,
                        o.CheckUserName,
                        o.InsuranceOrderId,
                        InsuranceOrderNo = o.InsuranceOrder.OrderNO
                    }).ToList();

            return Json(new { logList }, JsonRequestBehavior.AllowGet);
        }
        #endregion 

        #region  显示导入返回结果   ActionResult ImportInsuranceOrder()
        public ActionResult ImportInsuranceOrder()
        {
            ViewBag.ReturnInfo = TempData["ResponseResult"];
            return View();
        }
        #endregion

        #region  导入保单信息execl ActionResult ImportInsuranceOrderData()
        public ActionResult ImportInsuranceOrderData()
        {
            var responseResult = new ResponseResult();
            var file = Request.Files["importFile"];
            if (file != null)
            {
                string fileName = file.FileName;
                string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

                if (!string.IsNullOrEmpty(strFileExt) && (strFileExt.ToLower() == "xls") ||
                    strFileExt.ToLower() == "xlsx")
                {
                    //upload to server
                    var saveFileName = FileHelper.UploadFile(file, Server);
                    string serverName = Server.MapPath(saveFileName);

                    var dt = ExcelHelper.ExcelToTable(serverName);
                    var insuranceCompany = "第三方承保公司";
                    var insuranceCompanyBranch = "承保公司分公司";
                    var insuranceCategoryName = "保险产品类型";
                    var productTypeName = "被保险设备";//手机
                    var deviceType = "设备类型";//设备类型（分为三类新机、在用机)
                    var productName = "保险产品名称";
                    var saleVendor = "销售商户名称";
                    var saleRetailPrice = "经销商零售价";
                    var insuranceCompanyRetailPrice = "保险公司零售价";
                    var price = "中保金服结算价";
                    var thirdOrderNO = "第三方保单号";
                    var thirdUniqueNumber = "第三方系统唯一编号";
                    var orderStatus = "保单状态";
                    var userName = "被保险人";
                    var userPhone = "被保险人电话";
                    var certificateType = "证件类型";
                    var certificateNO = "证件号码";
                    var imei = "设备识别码";
                    var productBrandName = "品牌";
                    var productModelName = "型号";
                    var insuredAmount = "保额";
                    var createTime = "投保时间";
                    var serviceStartTime = "保险起期";
                    var serviceEndTime = "保险止期";
                    if (dt.Columns.Contains(insuranceCompany) &&
                        dt.Columns.Contains(insuranceCompanyBranch) &&
                        dt.Columns.Contains(insuranceCategoryName) &&
                        dt.Columns.Contains(productName) &&
                        dt.Columns.Contains(productTypeName) &&
                        dt.Columns.Contains(deviceType) &&
                        dt.Columns.Contains(saleVendor) &&
                        dt.Columns.Contains(saleRetailPrice) &&
                        dt.Columns.Contains(insuranceCompanyRetailPrice) &&
                        dt.Columns.Contains(price) &&
                        dt.Columns.Contains(thirdOrderNO) &&
                        dt.Columns.Contains(thirdUniqueNumber) &&
                        dt.Columns.Contains(orderStatus) &&
                        dt.Columns.Contains(userName) &&
                        dt.Columns.Contains(userPhone) &&
                        dt.Columns.Contains(certificateType) &&
                        dt.Columns.Contains(certificateNO) &&
                        dt.Columns.Contains(imei) &&
                        dt.Columns.Contains(productBrandName) &&
                        dt.Columns.Contains(productModelName) &&
                        dt.Columns.Contains(insuredAmount) &&
                        dt.Columns.Contains(createTime) &&
                        dt.Columns.Contains(serviceStartTime) &&
                        dt.Columns.Contains(serviceEndTime))
                    {
                        var result = new StringBuilder();
                        var sb = new StringBuilder();
                        int addSuccCount = 0;
                        int updateSuccCount = 0;
                        int addFaileCount = 0;
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            decimal insuredAmt = 0;
                            decimal salePrice = 0;
                            decimal insuranceCompanyPrice = 0;
                            decimal orderPrice = 0;
                            var orderTime = new DateTime();
                            var orderStartTime = new DateTime();
                            var orderEndTime = new DateTime();

                            DataRow drItem = dt.Rows[i];
                            bool userNameIsOK = !string.IsNullOrWhiteSpace(drItem[userName].ToString());
                            bool productTypeNameIsOK = !string.IsNullOrWhiteSpace(drItem[productTypeName].ToString());
                            bool insuranceCategoryNameIsOK = !string.IsNullOrWhiteSpace(drItem[insuranceCategoryName].ToString());
                            bool productNameIsOK = !string.IsNullOrWhiteSpace(drItem[productName].ToString());
                            bool thirdOrderNOIsOK = !string.IsNullOrWhiteSpace(drItem[thirdOrderNO].ToString());
                            if (string.IsNullOrWhiteSpace(drItem[thirdUniqueNumber].ToString()))
                            {
                                drItem[thirdUniqueNumber] = drItem[thirdOrderNO].ToString();
                            }
                            bool thirdUniqueNumberIsOK = !string.IsNullOrWhiteSpace(drItem[thirdUniqueNumber].ToString());
                            bool insuredAmountIsOK = decimal.TryParse(
                                    string.IsNullOrWhiteSpace(drItem[insuredAmount].ToString())
                                        ? "0"
                                        : drItem[insuredAmount].ToString(), out insuredAmt);
                            bool saleRetailPriceIsOK = decimal.TryParse(
                                    string.IsNullOrWhiteSpace(drItem[saleRetailPrice].ToString())
                                        ? "0"
                                        : dt.Rows[i][saleRetailPrice].ToString(), out salePrice);
                            bool insuranceCompanyRetailPriceIsOK = decimal.TryParse(
                                    string.IsNullOrWhiteSpace(drItem[insuranceCompanyRetailPrice].ToString())
                                        ? "0"
                                        : drItem[insuranceCompanyRetailPrice].ToString(), out insuranceCompanyPrice);
                            bool priceIsOK = decimal.TryParse(
                                    string.IsNullOrWhiteSpace(drItem[price].ToString())
                                        ? "0"
                                        : dt.Rows[i][price].ToString(), out orderPrice);
                            bool createTimeIsOK = DateTime.TryParse(drItem[createTime].ToString(), out orderTime);
                            bool serviceStartTimeIsOK = DateTime.TryParse(drItem[serviceStartTime].ToString(), out orderStartTime);
                            bool serviceEndTimeIsOK = DateTime.TryParse(drItem[serviceEndTime].ToString(), out orderEndTime);

                            //!string.IsNullOrWhiteSpace(dt.Rows[i][userPhone].ToString()) &&
                            //!string.IsNullOrWhiteSpace(dt.Rows[i][certificateType].ToString()) &&
                            //!string.IsNullOrWhiteSpace(dt.Rows[i][certificateNO].ToString()) &&
                            //!string.IsNullOrWhiteSpace(dt.Rows[i][deviceType].ToString()) &&
                            //!string.IsNullOrWhiteSpace(dt.Rows[i][imei].ToString()) &&
                            //!string.IsNullOrWhiteSpace(dt.Rows[i][productBrandName].ToString()) &&
                            //!string.IsNullOrWhiteSpace(dt.Rows[i][productModelName].ToString()) &&
                            if (userNameIsOK && productTypeNameIsOK && insuranceCategoryNameIsOK && productNameIsOK && thirdOrderNOIsOK && thirdUniqueNumberIsOK && insuredAmountIsOK && saleRetailPriceIsOK && insuranceCompanyRetailPriceIsOK && priceIsOK && createTimeIsOK && serviceStartTimeIsOK && serviceEndTimeIsOK)
                            {
                                InsuranceOrder existEntity = null;
                                if (
                                    !ServiceFactory.InsuranceOrderServiceInstance.IsExistByThirdUniqueNumber(
                                        CommonMethod.GetTrimStr(dt.Rows[i][thirdUniqueNumber].ToString()), ref existEntity))
                                {
                                    #region 新增
                                    var companyBranch = CommonMethod.GetTrimStr(drItem[insuranceCompanyBranch].ToString());
                                    var parentCompanyName = CommonMethod.GetTrimStr(drItem[insuranceCompany].ToString());
                                    var insuranceCompanyEntity =
                                        ServiceFactory.InsuranceCompanyServiceInstance.Load(companyBranch, parentCompanyName) ??
                                        new InsuranceCompany { ID = 0, CompanyName = companyBranch, ParentCompanyName = parentCompanyName };
                                    var obj = new InsuranceOrder
                                    {
                                        CardNo = string.Empty,
                                        CardPwd = string.Empty,
                                        VerificationCertificate = string.Empty,
                                        OrderNO = CommonMethod.GetNewOrderNo(),
                                        InsuranceCompanyID = insuranceCompanyEntity.ID,
                                        InsuranceCompany = insuranceCompanyEntity.ParentCompanyName,
                                        InsuranceCompanyBranch = insuranceCompanyEntity.CompanyName,
                                        ThirdUniqueNumber =
                                            CommonMethod.GetTrimStr(drItem[thirdUniqueNumber].ToString()),
                                        ThirdOrderNO = CommonMethod.GetTrimStr(drItem[thirdOrderNO].ToString()),
                                        InsuranceCategoryName =
                                            CommonMethod.GetTrimStr(drItem[insuranceCategoryName].ToString()),
                                        ProductName = CommonMethod.GetTrimStr(drItem[productName].ToString()),
                                        BuyType = (byte)InsuranceBuyType.NonActivationCodeBuy,
                                        Price = orderPrice,
                                        InsuredAmount = insuredAmt,
                                        WaitDays = 0,
                                        Effective = drItem[orderStatus].ToString() != "退保",
                                        OrderStatus =
                                            drItem[orderStatus].ToString() == "退保"
                                                ? (byte)InsuranceOrderStatus.Cancel
                                                : (byte)InsuranceOrderStatus.HadEffective,
                                        EffectiveDate = orderTime,
                                        ServiceStartTime = orderStartTime,
                                        ServiceEndTime = orderEndTime,
                                        PolicyPeriod = (orderEndTime - orderStartTime).Days,
                                        PolicyPeriodUnit = (byte)InsuranceOrderPeriodUnit.Day,
                                        UserName = CommonMethod.GetTrimStr(drItem[userName].ToString()),
                                        UserPhone = CommonMethod.GetTrimStr(drItem[userPhone].ToString()),
                                        CertificateType =
                                            (byte)CommonMethod.GetCertificateType(drItem[certificateType].ToString()),
                                        CertificateNO = CommonMethod.GetTrimStr(drItem[certificateNO].ToString()),
                                        ProductTypeName = CommonMethod.GetTrimStr(drItem[productTypeName].ToString()),
                                        IMEI = CommonMethod.GetTrimStr(drItem[imei].ToString()),
                                        ProductBrandName = CommonMethod.GetTrimStr(drItem[productBrandName].ToString()),
                                        ProductModelName = CommonMethod.GetTrimStr(drItem[productModelName].ToString()),
                                        DeviceType =
                                            (byte)CommonMethod.GetOrderDeviceType(drItem[deviceType].ToString()),
                                        SaleVendorName = CommonMethod.GetTrimStr(drItem[saleVendor].ToString()),
                                        SaleRetailPrice = salePrice,
                                        InsuranceCompanyRetailPrice = insuranceCompanyPrice,
                                        //OrderFromType = byte.Parse(fromType),
                                        CreateOrderTime = orderTime,
                                        CreateBy = CurrentUser.UserAccount,
                                        LastModifyBy = CurrentUser.UserAccount,
                                        LastModifyTime = DateTime.Now
                                    };

                                    #region Init some ID

                                    var product =
                                        ServiceFactory.ProductTypeServiceInstance.LoadByName(
                                            drItem[productTypeName].ToString());
                                    if (product != null)
                                    {
                                        obj.ProductTypeId = product.ID;
                                    }
                                    var brand =
                                        ServiceFactory.ProductBrandsServiceInstance.LoadByName(
                                            drItem[productBrandName].ToString());
                                    if (brand != null)
                                    {
                                        obj.ProductBrandId = brand.ID;

                                        var model = ServiceFactory.ProductModelsServiceInstance.LoadByName(brand.ID,
                                            drItem[productModelName].ToString());
                                        if (model != null)
                                        {
                                            obj.ProductModelId = model.ID;
                                        }
                                    }

                                    #endregion

                                    var entity =
                                        ServiceFactory.InsuranceOrderServiceInstance.AddEntities(obj);
                                    if (entity.ID > 0)
                                    {
                                        addSuccCount++;
                                    }
                                    else
                                    {
                                        addFaileCount++;
                                    }
                                    #endregion
                                }
                                else
                                {
                                    #region 更新

                                    existEntity.InsuranceCompany =
                                        CommonMethod.GetTrimStr(dt.Rows[i][insuranceCompany].ToString());
                                    existEntity.InsuranceCompanyBranch =
                                        CommonMethod.GetTrimStr(dt.Rows[i][insuranceCompanyBranch].ToString());
                                    existEntity.InsuranceCategoryName =
                                        CommonMethod.GetTrimStr(dt.Rows[i][insuranceCategoryName].ToString());
                                    existEntity.ProductName = CommonMethod.GetTrimStr(dt.Rows[i][productName].ToString());
                                    existEntity.Price = orderPrice;
                                    existEntity.InsuredAmount = insuredAmt;
                                    existEntity.WaitDays = 0;
                                    existEntity.EffectiveDate = orderTime;
                                    existEntity.ServiceStartTime = orderStartTime;
                                    existEntity.ServiceEndTime = orderEndTime;
                                    existEntity.PolicyPeriod = (orderEndTime - orderStartTime).Days;
                                    existEntity.PolicyPeriodUnit = (byte)InsuranceOrderPeriodUnit.Day;
                                    existEntity.UserName = CommonMethod.GetTrimStr(dt.Rows[i][userName].ToString());
                                    existEntity.UserPhone = CommonMethod.GetTrimStr(dt.Rows[i][userPhone].ToString());
                                    existEntity.CertificateType =
                                        (byte)CommonMethod.GetCertificateType(dt.Rows[i][certificateType].ToString());
                                    existEntity.CertificateNO =
                                        CommonMethod.GetTrimStr(dt.Rows[i][certificateNO].ToString());
                                    existEntity.ProductTypeName =
                                        CommonMethod.GetTrimStr(dt.Rows[i][productTypeName].ToString());
                                    existEntity.IMEI = CommonMethod.GetTrimStr(dt.Rows[i][imei].ToString());
                                    existEntity.ProductBrandName =
                                        CommonMethod.GetTrimStr(dt.Rows[i][productBrandName].ToString());
                                    existEntity.ProductModelName =
                                        CommonMethod.GetTrimStr(dt.Rows[i][productModelName].ToString());
                                    existEntity.DeviceType =
                                        (byte)CommonMethod.GetOrderDeviceType(dt.Rows[i][deviceType].ToString());
                                    existEntity.SaleVendorName =
                                        CommonMethod.GetTrimStr(dt.Rows[i][saleVendor].ToString());
                                    existEntity.SaleRetailPrice = salePrice;
                                    existEntity.InsuranceCompanyRetailPrice = insuranceCompanyPrice;
                                    existEntity.OrderStatus =
                                        dt.Rows[i][orderStatus].ToString() == "退保"
                                            ? (byte)InsuranceOrderStatus.Cancel
                                            : (byte)InsuranceOrderStatus.HadEffective;
                                    //OrderFromType = byte.Parse(fromType),
                                    //existEntity.CreateOrderTime = orderTime;
                                    existEntity.CreateBy = CurrentUser.UserAccount;
                                    existEntity.LastModifyBy = CurrentUser.UserAccount;
                                    existEntity.LastModifyTime = DateTime.Now;

                                    #region Init some ID

                                    var product =
                                        ServiceFactory.ProductTypeServiceInstance.LoadByName(
                                            dt.Rows[i][productTypeName].ToString());
                                    if (product != null)
                                    {
                                        existEntity.ProductTypeId = product.ID;
                                    }
                                    var brand =
                                        ServiceFactory.ProductBrandsServiceInstance.LoadByName(
                                            dt.Rows[i][productBrandName].ToString());
                                    if (brand != null)
                                    {
                                        existEntity.ProductBrandId = brand.ID;

                                        var model = ServiceFactory.ProductModelsServiceInstance.LoadByName(brand.ID,
                                            dt.Rows[i][productModelName].ToString());
                                        if (model != null)
                                        {
                                            existEntity.ProductModelId = model.ID;
                                        }
                                    }

                                    #endregion

                                    var flag =
                                        ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(existEntity);
                                    if (flag)
                                    {
                                        updateSuccCount++;
                                    }
                                    else
                                    {
                                        addFaileCount++;
                                    }
                                    #endregion
                                }
                            }
                            else
                            {
                                addFaileCount++;
                                sb.AppendFormat(
                                    "第{0}行验证不合法，第三方承保公司={1},承保公司分公司={2},被保险人={3},被保险人电话={4},证件类型={5},证件号码={6},被保险设备={7},设备类型={8},设备识别码={9},品牌={10},型号={11},保险产品类型={12},保险产品名称={13},保额={14},经销商零售价={15},保险公司零售价={16},中保金服结算价={17},投保时间={18},保险起期={19},保险止期={20},第三方保单号={21},销售商户名称={22}\r\n",
                                    i + 1,
                                    drItem[insuranceCompany],
                                    drItem[insuranceCompanyBranch],
                                    drItem[userName],
                                    drItem[userPhone],
                                    drItem[certificateType],
                                    drItem[certificateNO],
                                    drItem[productTypeName],
                                    drItem[deviceType],
                                    drItem[imei],
                                    drItem[productBrandName],
                                    drItem[productModelName],
                                    drItem[insuranceCategoryName],
                                    drItem[productName],
                                    drItem[insuredAmount],
                                    drItem[saleRetailPrice],
                                    drItem[insuranceCompanyRetailPrice],
                                    drItem[price],
                                    drItem[createTime],
                                    drItem[serviceStartTime],
                                    drItem[serviceEndTime],
                                    drItem[thirdOrderNO],
                                    drItem[saleVendor]);
                            }
                        }
                        result.AppendFormat("导入新增成功数量:{0},更新成功数量:{1},失败数量:{2}.提示信息:{3}", addSuccCount, updateSuccCount,
                            addFaileCount, sb);
                        responseResult.Message = result.ToString();
                    }
                    else
                    {
                        responseResult.Message = "导入列不合法，请下载导入模版.";
                    }
                }
                else
                {
                    responseResult.Message = "导入文件不合法，只能导入XLS或XLSX.";
                }
            }
            else
            {
                responseResult.Message = "请选择文件.";
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("ImportInsuranceOrder");
        }
        #endregion

        public ActionResult UnComplementInsuranceOrderList()
        {
            return View();
        }

        #region 补充保单信息
        public ActionResult ComplementInsuranceOrder(long id)
        {
            var insuranceOrder = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(id);
            return View(insuranceOrder);
        }
        public ActionResult SaveUnComplementInsuranceOrder(InsuranceOrder order)
        {
            var responseResult = new ResponseResult();
            var insuranceOrder = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(order.ID);
            if (insuranceOrder == null)
            {
                responseResult.Message = "订单不存在！";
                TempData["ResponseResult"] = responseResult;
                return RedirectToAction("ComplementInsuranceOrder", new { id = order.ID });
            }
            else
            {
                insuranceOrder.LastModifyBy = CurrentUser.UserAccount;
                insuranceOrder.LastModifyTime = DateTime.Now;
                insuranceOrder.InsuranceCategoryName = order.InsuranceCategoryName;
                insuranceOrder.ProductName = order.ProductName;
                insuranceOrder.ProductTypeId = order.ProductTypeId;
                insuranceOrder.CertificateType = order.CertificateType;
                insuranceOrder.InsuranceCompanyBranch = order.InsuranceCompanyBranch;
                insuranceOrder.DeviceType = order.DeviceType;
                insuranceOrder.ProductBrandId = order.ProductBrandId;
                insuranceOrder.ProductBrandName = order.ProductBrandName;
                insuranceOrder.SaleVendorId = order.SaleVendorId;
                insuranceOrder.SaleVendorName = order.SaleVendorName;
                insuranceOrder.ProductModelId = order.ProductModelId;
                insuranceOrder.ProductModelName = order.ProductModelName;
                insuranceOrder.IMEI = order.IMEI;
                insuranceOrder.ThirdUniqueNumber = order.ThirdUniqueNumber.Trim();
                insuranceOrder.ThirdOrderNO = order.ThirdOrderNO.Trim();
                insuranceOrder.UserName = order.UserName;
                insuranceOrder.UserPhone = order.UserPhone.Trim();
                insuranceOrder.ServiceStartTime = order.ServiceStartTime;
                insuranceOrder.ServiceEndTime = order.ServiceEndTime;
                insuranceOrder.CertificateNO = string.IsNullOrEmpty(order.CertificateNO) ? "" : order.CertificateNO.Trim();
                insuranceOrder.CreateOrderTime = order.CreateOrderTime > DateTime.MinValue
                    ? order.CreateOrderTime
                    : DateTime.Now;
                insuranceOrder.InsuredAmount = order.InsuredAmount;
                insuranceOrder.OrderStatus = order.OrderStatus;
                responseResult.Success = ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(insuranceOrder);
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("ComplementInsuranceOrder", new { id = order.ID });
        }
        #endregion


        #region 待审核保单界面，客服开启/关闭审核工作
        public ActionResult OpenCheckTask()
        {
            SystemUser user = ServiceFactory.SystemUserServiceInstance.Load(CurrentUser.ID);
            user.IsCheckOnline = 1;
            bool re = ServiceFactory.SystemUserServiceInstance.UpdateEntities(user);
            return Json(new { Result = re }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CloseCheckTask()
        {
            SystemUser user = ServiceFactory.SystemUserServiceInstance.Load(CurrentUser.ID);
            user.IsCheckOnline = 0;
            bool re = ServiceFactory.SystemUserServiceInstance.UpdateEntities(user);
            return Json(new { Result = re }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
